package service

import (
	"context"
	"encoding/json"
	"entry_task/backend/src/utils"
	api "entry_task/entry_api/service"
	"entry_task/entry_core/src/dao"
	"entry_task/entry_core/src/model"
	"entry_task/entry_core/src/mredis"
	"fmt"
	"github.com/go-redis/redis/v8"
	uuid "github.com/satori/go.uuid"
	"time"
)

type UserInfoServiceImpl struct {
}

func (impl *UserInfoServiceImpl) Login(ctx context.Context, req *api.LoginReq) (*api.TokenMessage, error) {
	// 1、查询用户名下的用户
	userInfo := dao.UserInfoDao().QueryByUsername(req.Username)
	// 密码做sh256哈希
	cryptoPassword := utils.LoginCrypto(req.Password)
	var token = ""

	if userInfo != nil && userInfo.Password == cryptoPassword {
		userInfo.Password = ""
		// 验证成功！！！生成token
		token = uuid.NewV4().String()
		rdb := mredis.GetRedisClient()
		jsonByte, err2 := json.Marshal(userInfo)
		utils.CheckErr(err2)
		err := rdb.Set(ctx, mredis.Token+token, string(jsonByte), mredis.TokenExp*time.Second).Err()
		utils.CheckErr(err)
	}
	return &api.TokenMessage{Token: token}, nil
}

func (impl *UserInfoServiceImpl) GetById(ctx context.Context, req *api.UserInfoReq) (*api.UserInfoResp, error) {
	userInfo := dao.UserInfoDao().QueryById(req.Id)
	if userInfo == nil {
		return nil, nil
	}
	return &api.UserInfoResp{Id: userInfo.Id,
		Username:          userInfo.Username,
		ProfilePictureUrl: userInfo.ProfilePictureUrl,
		Nickname:          userInfo.Nickname,
		UpdateTime:        utils.StandardFormat(userInfo.UpdateTime),
		CreateTime:        utils.StandardFormat(userInfo.CreateTime),
	}, nil
}

func (impl *UserInfoServiceImpl) GetByToken(ctx context.Context, req *api.TokenMessage) (*api.UserInfoResp, error) {
	// 从redis中获取对象
	rdb := mredis.GetRedisClient()
	value, err := rdb.Get(ctx, mredis.Token+req.Token).Result()
	if err == redis.Nil {
		fmt.Printf("token: %s does not exist", req.Token)
		return nil, nil
	} else if err != nil {
		panic(err)
	}
	fmt.Println("token value : ", value)
	userInfo := model.UserInfoTab{}
	err = json.Unmarshal([]byte(value), &userInfo)
	utils.CheckErr(err)
	//userInfo := dao.UserInfoDao().QueryById(req)
	return &api.UserInfoResp{Id: userInfo.Id}, nil
}

func (impl *UserInfoServiceImpl) UpdateUserInfo(ctx context.Context, req *api.UpdateUserInfoReq) (*api.UpdateUserInfoResp, error) {
	userInfo := &model.UserInfoTab{
		Id:                req.Id,
		Nickname:          req.Nickname,
		ProfilePictureUrl: req.ProfilePictureUrl,
	}
	num := dao.UserInfoDao().UpdateById(userInfo)
	success := false
	if num > 0 {
		success = true
	}
	return &api.UpdateUserInfoResp{Success: success}, nil
}
